/**
 * @description 可以生成一个redux store
 */
function createStore(reducer, state) {
  // 表示redux 总状态
  let rootState = null
  // 订阅所有的事件
  const nextListeners = []

  const dispatch = (action) => {
    rootState = reducer(rootState || state, action)

    nextListeners.forEach((listener) => listener())
  }

  const subscribe = (listener) => {
    const index = nextListeners.push(listener)

    return () => {
      nextListeners.splice(index, 1)
    }
  }

  // 返回store
  const getState = () => {
    return rootState
  }
  // 初期执行
  dispatch({ type: '@@init' })

  const store = {
    dispatch,
    subscribe,
    getState
  }
  return store
}

export { createStore }
